package main

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"gitee.com/ling_boogie/mahjong-helper/util"
)

func newShantenLogFilePath(dateStr string, nickName string, accountID string) (filePath string, err error) {
	// 获取或者创建shanten日志
	const logDir = "shanten"
	if err = os.MkdirAll(logDir, os.ModePerm); err != nil {
		return
	}
	fileName := fmt.Sprintf("shanten-%s-%s-%s.log", dateStr, nickName, accountID)
	filePath = filepath.Join(logDir, fileName)
	return filepath.Abs(filePath)
}
func PrintFirstShantenLog(nickName string, accountID string, shanten int) {
	// 设置日志输出到 shanten/shanten-xxx.log
	if debugMode {
		fmt.Printf("%s-%s-%d\n", nickName, accountID, shanten)
	}
	year, month, day := DateYmdInts()
	dateStr := strconv.Itoa(year) + "#" + strconv.Itoa(month)
	filePath, err := newShantenLogFilePath(dateStr, nickName, accountID)
	if err != nil {
		return
	}
	logFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		return
	}
	//及时关闭file句柄
	defer func(logFile *os.File) {
		err := logFile.Close()
		if err != nil {
			util.OrangevillePrint("[ERROR] printFirstShantenLog: log open failed.")
			return
		}
	}(logFile)
	//写入文件时，使用带缓存的 *Writer
	write := bufio.NewWriter(logFile)

	inStr := fmt.Sprintf(
		"{\"year\":%d, "+
			"\"month\":%d, "+
			"\"day\":%d, "+
			"\"shanten\":%d}"+
			"\n",
		year, month, day, shanten)
	_, err = write.WriteString(inStr)
	if err != nil {
		return
	}
	//Flush将缓存的文件真正写入到文件中
	err = write.Flush()
	if err != nil {
		return
	}
}

// DateYmdInts 获取日期的年月日
func DateYmdInts() (int, int, int) {
	timeNow := time.Now()
	year, month, day := timeNow.Date()
	return year, int(month), day
}
